﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data.EntityClient;
using System.Data.Metadata.Edm;
using System.Data.Common;
using System.Data.Entity;

namespace EZMemoLib
{
    public class ConfigOp
    {
        public const string CONFIGNAME_GlobalFlow = "GlobalFlow";
        //{0} is csdl name, {1} is database file full path
        public const string ConnectionStringFormat = "metadata=\"res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl\";provider=System.Data.SQLite;provider connection string=\"data source={1}\"";
        private const string SystemMetadataName = "EZMemo";
        private const string BookMetadataName = "MemoBook";
        private const string DBFileFolder = "Data";
        private const string DBFileName = "EZMemo2";
        private const string DBFileExt = ".db3";


        public static string GetEFConnectionStringForBook( string bookID)
        {
            string metadataName = BookMetadataName;
            string dbFileName = string.Format("{0}{1}", bookID, DBFileExt);

            return GetEFConnectionString(metadataName, dbFileName);
        }

        public static string GetEFConnectionString()
        {
            string metadataName = SystemMetadataName;
            string dbFileName = string.Format("{0}{1}", DBFileName, DBFileExt);

            return GetEFConnectionString(metadataName, dbFileName);
        }

        public static string GetEFConnectionString(string metadataName, string dbFileName)
        {
            //AppDomain.SetData(("DataDirectory", objValue) 
            //AppDomain appd = AppDomain.CurrentDomain;
            //if (appd != null)
            //{
            //    string dataDirectory = (string)appd.GetData("DataDirectory");
            //}

            if (string.IsNullOrEmpty(metadataName))
            {
                metadataName = SystemMetadataName;
            }
            string dbFilePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location),DBFileFolder, dbFileName);
            string connectionString = string.Format(ConnectionStringFormat, metadataName, dbFilePath);

            return connectionString;
        }

        public static EntityConnection GetEFConnection()
        {

            // Specify the provider name, server and database.
            string providerName = "System.Data.SqlClient";
            string serverName = ".";
            string databaseName = "AdventureWorks";

            // Initialize the connection string builder for the
            // underlying provider.
            var sqlBuilder =
                new System.Data.SqlClient.SqlConnectionStringBuilder();

            // Set the properties for the data source.
            sqlBuilder.DataSource = serverName;
            sqlBuilder.InitialCatalog = databaseName;
            sqlBuilder.IntegratedSecurity = true;

            // Build the SqlConnection connection string.
            string providerString = sqlBuilder.ToString();

            //providerString = GetEFConnectionString();

            // Initialize the EntityConnectionStringBuilder.
            EntityConnectionStringBuilder entityBuilder =
                new EntityConnectionStringBuilder();

            //Set the provider name.
            entityBuilder.Provider = providerName;

            // Set the provider-specific connection string.
            entityBuilder.ProviderConnectionString = providerString;

            // Set the Metadata location.
            entityBuilder.Metadata = @"res://*/AdventureWorksModel.csdl|
                            res://*/AdventureWorksModel.ssdl|
                            res://*/AdventureWorksModel.msl";
            string str = entityBuilder.ToString();

            str = GetEFConnectionString();

            //MetadataWorkspace mw = new MetadataWorkspace ();
            //mw.RegisterItemCollection 
            
            var connection = new EntityConnection( str);
            //connection.StoreConnection = new DbConnection();
            
                //= "name=EZMemoEntities3";
            

            using (EntityConnection conn = connection )
            {
                var mw = conn.GetMetadataWorkspace();
                conn.Open();

                Console.WriteLine("Just testing the connection.");
                conn.Close();
            }

            var dbcontext = new DBContext(str);
            var dbconn = dbcontext.Database.Connection;
            //return (EntityConnection)dbconn;

            //dbcontext.MemoCategories.Add(new MCategory { CategoryName = "test" });
            //dbcontext.SaveChanges ();

            return connection ;
        }


        public static int SaveConfig(string name, string value)
        {
            EZMemoEntities database = new EZMemoEntities();

            var config = database.MemoConfig.Where(c => c.ConfigName == name).FirstOrDefault ();
            if (config == null)
            {
                config = new MemoConfig { ConfigName = name, ConfigValue = value, ConfigValueType = value.GetType().ToString() };
                database.AddToMemoConfig(config);
            }
            else
            {
                config.ConfigValue = value ;
            }

            int rc = database.SaveChanges();
            return rc;
        }

        public static string LoadConfig( string name )
        {
            var database = new EZMemoEntities();

            var config = database.MemoConfig.Where(c => c.ConfigName == name).FirstOrDefault ();

            string configvalue = null;
            if (config != null)
                configvalue = config.ConfigValue;

            return configvalue;
        }
    }
}
